var COS = require("cos-js-sdk-v5");
import Vue from "vue";

var Bucket = "bucket1-1258909722";
var Region = "ap-shanghai"; /* 存储桶所在地域，必须字段 */

var cos = new COS({
  getAuthorization: function(options, callback) {
    // 异步获取临时密钥
    Vue.prototype.$axios
      .get("/uploadSignature/temSecret", {
        bucket: Bucket,
        region: Region,
      })
      .then((data) => {        
        var credentials = data && data.credentials;
        if (!data || !credentials) return console.error("credentials invalid");
        callback({
          TmpSecretId: credentials.tmpSecretId,
          TmpSecretKey: credentials.tmpSecretKey,
          XCosSecurityToken: credentials.sessionToken,
          // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
          StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
          ExpiredTime: data.expiredTime, // 时间戳，单位秒，如：1580000900
        });
      });
  },
});

function upload(fileName, file, onProgress, onSuccess) {  
  cos.putObject(
    {
      Bucket: Bucket /* 必须 */,
      Region: Region /* 存储桶所在地域，必须字段 */,
      Key: "/admin/doc/" + fileName /* 必须 */,
      StorageClass: "STANDARD",
      Body: file, // 上传文件对象
      onProgress: function(progressData) {        
        onProgress(progressData);
      },
    },
    function(err, data) {      
      console.log(err || data);
      if (err) {
      } else {
        onSuccess(data);
      }
    }
  );
}

export { upload };
